package com.ggboy.item_bank.controller;

import com.ggboy.item_bank.beans.User;
import com.ggboy.item_bank.service.SnoService;
import com.ggboy.item_bank.service.SpecialtyService;
import com.ggboy.item_bank.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;//向上转型自动注入
    @Resource
    private SpecialtyService specialtyService;
    @Resource
    private SnoService snoService;

    @RequestMapping("/login")//指定RequestMapping,请求路径参数与方法参数匹配上时会自动注入，则不用额外在参数上使用注解
    public String login(String username, String password, Model model, HttpSession session){//对登录的用户进行判断用的
        try {
//            userService.checkLogin(username,password);
            Subject subject = SecurityUtils.getSubject();//获取当前用户
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);//封装用户登录的数据
            subject.login(token);//执行到这里会跳到认证方法处
            User user = userService.isRegister(username);
            if (user.getFlag() == 1){
                session.setAttribute("user",user);//存用户
                String spName = specialtyService.selectSpNameById(user.getTeacherSpecialty());//获取用户对应的学院
                String name = user.getTeacherName();//获取用户的学生姓名
                //把用户和学生姓名存起来，登录后取出显示用
                model.addAttribute("TeacherName",name);
                model.addAttribute("SpecialtyName",spName);
                return "index";//进入主页
            }else{
                model.addAttribute("msg","当前账号被禁用，请联系管理员");
                return "login";
            }
        } catch (Exception e) {
            model.addAttribute("msg","用户名或密码错误");
            return "login";
        }
    }

    @RequestMapping("/register")//注册用的
    public String register(Model model, User user,HttpSession session){
        String a1 = "";
        if (user.getRname()!=null&&user.getTeacherSpecialty()!=null) {//判断学院和身份有没有选择
            if (snoService.select(user.getTeacherId()) != null) {//查找学号是否在籍
                a1 = userService.addUser(user);//添加用户，并对账号进行判断返回错误信息或为空
                if (a1==null) {//无错误信息说明添加成功返回登录页
                    return "login";
                }else {//有错误信息说明注册失败返回注册页
                    model.addAttribute("NOTT", a1);
                    return "register";
                }
            } else {
                model.addAttribute("NOTT", "学号不存在");
                return "register";
            }
        }else {
            model.addAttribute("NOTT", "身份和学院需选择");
            return "register";
        }

    }

}
